package bosc.cn.handler;

import bosc.cn.constant.PrcStsEnum;
import bosc.cn.constant.RetCdEnum;
import cn.dto.common.CommonResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tianshq
 * @date 2025/9/8 22:55
 * @description ValidationExceptionHandler
 */
@RestControllerAdvice
public class ValidationExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResponse handleValidationExceptions(
            MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        CommonResponse response = new CommonResponse();
        response.setRetCd(RetCdEnum.SUCCESS.getCode());
        response.setRetMsg(RetCdEnum.SUCCESS.getMsg());
        response.setRetTm(LocalDateTime.now());
//        response.setPrcMsg(errors.toString());
//        response.setPrcSts(PrcStsEnum.PARAM_ERROR.getCode());
        return response;
    }
}
